package com.ideaction.service;

import com.ideaction.entity.mail.PlayerMailData;
import com.ideaction.entity.mail.SysMail;
import com.ideaction.entity.mail.UserMail;
import com.ideaction.entity.mail.filter.MailSimpleFilter;
import com.ideaction.game.utils.SimpleDBUtil;
import com.ideaction.globalconst.ParamKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 邮件系统服务,系统邮件加一个缓存
 *
 * @author ZGame
 */
@Service
@Slf4j
public class MailService {
    
    @Autowired
    private MongoTemplate funcMongoTemplate;
    
    @Autowired
    private MongoTemplate playerMongoTemplate;
    
    @Autowired
    private MailSimpleFilter mailFilter;
    
    /**
     * 获取系统邮件
     *
     * @return
     */
    @Cacheable(cacheNames = "sysmail", key = "'sysmail'")
    public List<SysMail> getSystemMail(PlayerMailData playerMailData, Map<String, String> paramMap) {
        final Map<String, Integer> mailStatus = new HashMap<String, Integer>();
        if (playerMailData != null) {
            mailStatus.putAll(playerMailData.getMailStatus());
        }
        List<SysMail> list = funcMongoTemplate.findAll(SysMail.class);
        log.info("缓存过期,从mongo加载 sysMailList 数据");
        // 筛选
        list = list.stream().filter(e -> mailFilter
                .canShow(e, mailStatus, paramMap.get(ParamKey.CHANNEL), paramMap.get(ParamKey.CHANNEL)))
                .collect(Collectors.toList());
        return list;
    }
    
    /**
     * 获取个人邮件
     *
     * @return
     */
    public List<UserMail> getPersonalMail(PlayerMailData playerMailData) {
        List<UserMail> list = playerMailData.getUserMailList();
        list = list.stream().filter(e -> mailFilter.canShow(e, playerMailData.getMailStatus()))
                .collect(Collectors.toList());
        return list;
    }
    
    /**
     * 获取玩家个人邮件保存数据(个人邮件和邮件状态)
     *
     * @param userId
     * @return
     */
    public PlayerMailData getPlayerMailData(String userId) {
        return SimpleDBUtil
                .findOtherSnapObj(PlayerMailData.class, playerMongoTemplate, userId, "RecordData", "playerMailData");
    }
}
